import {reqfind, reqmain} from "@/common/api";
import * as actionType from "@/common/store/constants";

const initialState = {
  page: 1,
  finddata: [],
  isLoading: false
}

// action types
export const types = {
  CHANGE_FINDDATA: "find/CHANGE_FINDDATA",
  CHANGE_LOADING: "find/CHANGE_LOADING"
};

export const changeMainData = (data) => {
  return {
    type: actionType.CHANGE_TESLADATA,
    data: data
  }
}

export const getMainData = () => {
  // dispatch一个同步任务
  return (dispatch) => {
    reqmain().then((res) => {
      dispatch(changeMainData(res.data))
    }).catch(() => {
      console.log('出错了');
    })
  }
}

export const getFindData = () => {
  return (dispatch) => {
    dispatch(setIsLoading(true))
    reqfind(1).then((res) => {
      dispatch(changeFindData(res.data))
    }).catch(() => {
      console.log('出错了');
      dispatch(setIsLoading(false))
    })
  }
}

export const changeFindData = (data) => {
  return {
    type: types.CHANGE_FINDDATA,
    data: data
  }
}

function setIsLoading(isLoading) {
  return {
    type: types.CHANGE_LOADING,
    data: isLoading
  }
}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case types.CHANGE_FINDDATA:
      // let newsList = [...state.finddata, ...action.data]
      // return {...state, finddata: newsList, isLoading: false}
      return {...state, finddata: action.data, isLoading: false}
    case types.CHANGE_LOADING:
      return {...state, isLoading: action.data}
    default:
      return state;
  }
}

export default reducer;
